package com.wasu.shiro.handler;

import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.wasu.bean.User;
import com.wasu.service.OrderJedis;
import com.wasu.util.MD5;

/**
 * 一、认证过程： 1、表单输入的用户名和密码会被封装到 UsernamePasswordToken对象
 * 2、在Realm子类构造并返回AuthenticationInfo对象 二、授权过程
 * 
 * @author zhouyang
 *
 */
@RequestMapping(value = "/shiro")
@Controller
public class LoginHandler {
	private static Logger log = Logger.getLogger(LoginHandler.class);

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String login(@RequestParam("username") String username, @RequestParam("password") String password) {

		Subject currentUser = SecurityUtils.getSubject();
		if (!currentUser.isAuthenticated()) {
			UsernamePasswordToken token = new UsernamePasswordToken(username, password, true);
			currentUser.login(token); // 调用自定义 Realm子类 完成登录认证
		}

		log.info("sessionid:"+currentUser.getSession().getId()+"-------会话时间："+currentUser.getSession().getTimeout()/1000+"s");
		
//		Session session = OrderJedis.getSession(""+currentUser.getSession().getId().toString());
//		log.info(info.getRoles().toString());
		//org.apache.shiro.subject.support.DefaultSubjectContext.PRINCIPALS_SESSION_KEY 保存 principal  
		//org.apache.shiro.subject.support.DefaultSubjectContext.AUTHENTICATED_SESSION_KEY 保存 boolean是否登陆 

		return "redirect:/index.jsp";
	}

	@RequestMapping(value = "/register")
	public String register(User user) {

		OrderJedis.adduser("users", user.getUsername(), MD5.sign(user.getUsername(),user.getPassword(), "utf-8"));

		return "redirect:/login.jsp";
	}
}
